import axios from "axios";
import qs from "qs";

axios.interceptors.request.use(
  (config) => config,
  (err) => Promise.reject(err)
);

axios.interceptors.response.use(
  (res) => {
    return Promise.resolve(res.data);
  },
  (err) => {
    console.log(err.response);
    // if (err.response && err.response.status === 401 && err.response.data.message === "Unauthenticated.") {
    //   localStorage.removeItem("token");
    //   window.$router.replace({
    //     path: "/login",
    //   });
    // }
    return Promise.reject(err);
  }
);

export const requestMethod = {
  GET: "get",
  POST: "post",
  PUT: "put",
  DELETE: "delete",
};

export const requestType = {
  DEFAULT: "application/x-www-form-urlencoded",
  JSON: "application/json",
  FILE: "multipart/form-data",
};

export const requestDuration = {
  STANDARD: 10000,
  FILE: 60000,
  LONG: 90000,
};

/**
 * 创建请求方法
 * @param {object} config={} 请求配置
 * @param {object} data={} 请求体参数
 * @param {object} params={} url 附加参数
 * @returns {any} 返回 axios 对象
 */
export const request = (config = {}, data = {}, params = {}) => {
  if (config.qs) {
    data = qs.stringify(data);
  }
  return axios({
    url: config.url || "",
    method: config.method || requestMethod.GET,
    headers: {
      "Content-Type": config.type || requestType.DEFAULT,
      ...config.headers,
    },
    responseType: config.responseType,
    timeout: config.timeout || requestDuration.STANDARD,
    onUploadProgress: config.uploadCallback || (() => null),
    data,
    params,
  });
};
